<template>
  <div class="modal-overlay" @click.self="close">
    <div class="modal-content">
      <div class="modal-header">
        <h3>{{ isEditing ? '编辑课程' : '添加课程' }}</h3>
        <button class="close-btn" @click="close">×</button>
      </div>

      <form @submit.prevent="submitForm">
        <div class="form-grid">
          <div class="form-group">
            <label>课程代码 *</label>
            <input 
              v-model="formData.courseCode" 
              required 
              placeholder="如：CS101"
              :disabled="isEditing"
            >
          </div>

          <div class="form-group">
            <label>课程名称 *</label>
            <input 
              v-model="formData.courseName" 
              required 
              placeholder="输入课程名称"
            >
          </div>

          <div class="form-group">
            <label>学分 *</label>
            <input 
              v-model="formData.credits" 
              type="number" 
              min="1" 
              max="10" 
              required
            >
          </div>

          <div class="form-group">
            <label>状态</label>
            <select v-model="formData.status">
              <option :value="1">启用</option>
              <option :value="0">禁用</option>
            </select>
          </div>

          <div class="form-group full-width">
            <label>课程描述</label>
            <textarea 
              v-model="formData.description" 
              rows="3" 
              placeholder="输入课程描述"
            ></textarea>
          </div>
        </div>

        <div class="modal-actions">
          <button type="button" class="btn-cancel" @click="close">取消</button>
          <button type="submit" class="btn-submit" :disabled="loading">
            {{ loading ? '保存中...' : (isEditing ? '更新' : '创建') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue';
import { courseApi } from '@/api/course';

export default {
  name: 'CourseModal',
  props: {
    course: {
      type: Object,
      default: null
    }
  },
  emits: ['close', 'saved'],
  setup(props, { emit }) {
    const loading = ref(false);
    const isEditing = computed(() => !!props.course);
    
    const formData = ref({
      courseCode: '',
      courseName: '',
      credits: 3,
      status: 1,
      description: ''
    });

    // 先定义resetForm函数
    const resetForm = () => {
      formData.value = {
        courseCode: '',
        courseName: '',
        credits: 3,
        status: 1,
        description: ''
      };
    };

    // 使用watch监听props变化
    watch(() => props.course, (newCourse) => {
      if (newCourse) {
        formData.value = { 
          courseCode: newCourse.courseCode || '',
          courseName: newCourse.courseName || '',
          credits: newCourse.credits || 3,
          status: newCourse.status !== undefined ? newCourse.status : 1,
          description: newCourse.description || ''
        };
      } else {
        resetForm();
      }
    }, { immediate: true });

    const close = () => {
      emit('close');
    };

    // src/components/CourseModal.vue - 修改submitForm方法
const submitForm = async () => {
  if (!formData.value.courseCode.trim()) {
    alert('请输入课程代码');
    return;
  }
  if (!formData.value.courseName.trim()) {
    alert('请输入课程名称');
    return;
  }

  loading.value = true;
  try {
    if (isEditing.value) {
      // 编辑课程：确保包含courseId
      const submitData = {
        courseId: props.course.id, // 关键：添加课程ID
        courseCode: formData.value.courseCode,
        courseName: formData.value.courseName,
        credits: formData.value.credits,
        status: formData.value.status,
        description: formData.value.description
      };
      console.log('📝 编辑课程提交数据:', submitData);
      await courseApi.updateCourse(submitData);
    } else {
      // 新增课程：不需要courseId
      const submitData = {
        courseCode: formData.value.courseCode,
        courseName: formData.value.courseName,
        credits: formData.value.credits,
        status: formData.value.status,
        description: formData.value.description
      };
      console.log('➕ 新增课程提交数据:', submitData);
      await courseApi.createCourse(submitData);
    }
    
    emit('saved');
  } catch (error) {
    console.error('保存课程失败:', error);
    const errorMsg = error.response?.data?.message || error.message || '操作失败';
    alert(`操作失败: ${errorMsg}`);
  } finally {
    loading.value = false;
  }
};

    return {
      formData,
      isEditing,
      loading,
      close,
      submitForm
    };
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90vw;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #666;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  padding: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #3498db;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.btn-cancel, .btn-submit {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
}

.btn-submit {
  background: #3498db;
  color: white;
}

.btn-submit:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn-submit:hover:not(:disabled) {
  background: #2980b9;
}
</style>